package com.server.llh.llhserverwork.activity.food;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.lelaohui.net.BaseLeLaohuiAcitivity;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.NetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;

import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.adapter.AccountAdapter;
import com.server.llh.llhserverwork.adapter.OrderInfoAdapter;
import com.server.llh.llhserverwork.bean.Account;
import com.server.llh.llhserverwork.bean.AccountConstant;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.FoodOrderInfosBean;
import com.server.llh.llhserverwork.bean.PayList;
import com.server.llh.llhserverwork.utils.ListViewHeightUtil;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.view.AddListView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ZTF on 2017-06-15.
 * 订单支付
 */

public class FoodOrderPayActivity extends BaseLeLaohuiAcitivity {
    public static final String TAG = "FoodOrder";
    @BindView(R.id.left_btn)
    ImageButton leftBtn;
    @BindView(R.id.titlebar_text)
    TextView titlebarText;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.order_num)
    TextView orderNum;
    @BindView(R.id.order_down_time)
    TextView orderDownTime;
    @BindView(R.id.order_paystatus)
    TextView orderPaystatus;
    @BindView(R.id.llh_order_server)
    AddListView llhOrderServer;
    @BindView(R.id.order_money)
    TextView orderMoney;
    @BindView(R.id.order_youhui)
    TextView orderYouhui;
    @BindView(R.id.order_pay_money)
    TextView orderPayMoney;
    @BindView(R.id.go_pay)
    TextView goPay;
    @BindView(R.id.go_quit_order)
    TextView goQuitOrder;
    @BindView(R.id.zhifu_Style)
    TextView zhifuStyle;
    @BindView(R.id.zhifu_card)
    TextView zhifuCard;
    @BindView(R.id.pay_sp)
    Spinner paySp;
    @BindView(R.id.llh_pay)
    LinearLayout llhPay;
    @BindView(R.id.text_money)
    TextView textMoney;
    @BindView(R.id.text_money_count)
    TextView textMoneyCount;
    @BindView(R.id.btn_commint)
    Button btnCommint;
    @BindView(R.id.bottom_view)
    RelativeLayout bottomView;
    @BindView(R.id.llh_pay_bottom)
    LinearLayout llhPayBottom;
    FoodOrderInfosBean.DataBean foodOrderData = null;
    private int payTypeInt, orderIdInt;
    private String idlong, orgIds;
    private double totalMoney, balances;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        titlebarText.setText("订单支付");
        btnCommint.setText("确认支付");
        if (getIntent() != null) {
            foodOrderData = (FoodOrderInfosBean.DataBean) getIntent().getSerializableExtra("foodOrderData");
            if (foodOrderData != null) {
                totalMoney = foodOrderData.getTotalMoney();
                orderIdInt = foodOrderData.getOrderId();
                textMoney.setText("金额：¥ " + foodOrderData.getTotalMoney());
                orderNum.setText("订单编号：" + foodOrderData.getOrderCode());
                orderDownTime.setText("下单时间" + foodOrderData.getAddTime());
                orderPayMoney.setVisibility(View.INVISIBLE);
                if (foodOrderData.getPayStatus() == 0) {
                    orderPaystatus.setText("未支付");
                } else if (foodOrderData.getPayStatus() == 1) {
                    orderPaystatus.setText("已支付");
                } else if (foodOrderData.getPayStatus() == 2) {
                    orderPaystatus.setText("退款成功");
                } else if (foodOrderData.getPayStatus() == 3) {
                    orderPaystatus.setText("退款处理中");
                }
                if ((Constants.ORDER_WAITE_CONSUME + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("待客户就餐");
                } else if ((Constants.ORDER_WAIT_SEND_STATUS + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("待配送");
                } else if ((Constants.ORDER_SENDING_STATUS + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("配送中");
                } else if ((Constants.ORDER_SEND_OVER_STATUS + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("配送成功");
                } else if ((Constants.ORDER_SUCESS_OVER_STATUS + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("交易成功");
                } else if ((Constants.ORDER_CLOSE_OVER_STATUS + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("交易关闭");
                } else if ((Constants.ORDER_CANCEL_SUCCESS_STATUS + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("订单已取消");
                } else if ((Constants.ORDER_REFUNDING_STATUS + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("退款中");
                } else if ((Constants.ORDER_REFUND_OVER_STATUS + "").equals(foodOrderData.getOrderStatus())) {
                    orderPaystatus.setText("退款成功");
                }
                OrderInfoAdapter orderInfoAdapter = new OrderInfoAdapter(this, foodOrderData.getWapDietInfoList());
                llhOrderServer.setAdapter(orderInfoAdapter);
                ListViewHeightUtil.setListViewHeightBasedOnChildren(llhOrderServer);
                orderMoney.setText("订单金额：¥ " + foodOrderData.getTotalMoney());
                orderYouhui.setText("优惠：¥ 0.00");
                goPay.setVisibility(View.GONE);
                goQuitOrder.setVisibility(View.GONE);
            }

        }

        paySp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                payTypeInt = accountList.get(position).getAcctype();
                idlong = accountList.get(position).getAccid();
                orgIds = accountList.get(position).getOrgId();
                balances = accountList.get(position).getBalance();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    /**
     * 支付方式
     *
     * @param getAcctype
     * @return
     */
    public PayList payListDate(String id, int getAcctype, double balanceD, String orgIds, int orderid) {
        PayList payList = new PayList();
        if (getAcctype == 1) {
            payList.add(id, AccountConstant.PayType.CASH_ACCOUNT, balanceD, orgIds);
        } else if (getAcctype == 7 || getAcctype == 6) {
            payList.add(id, AccountConstant.PayType.ACTIVE_CARD, balanceD, orgIds);
        }
        payList.setOrderid("C_"+orderid);
        payList.setConsumeType(AccountConstant.ConsumeType.CONSUME_CATERING);
        return payList;
    }

    @Override
    protected void onResume() {
        accoutByRelated(mUserId);
        super.onResume();
    }

    @OnClick({R.id.left_btn, R.id.btn_commint})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_btn:
                onBackPressed();
                break;
            case R.id.btn_commint:
                if (balances < totalMoney) {
                    T.showAnimToast(getApplicationContext(), "账户余额不足，请切换其他账户！");
                    return;
                } else {
                    PayList payList = payListDate(idlong, payTypeInt, totalMoney, orgIds, orderIdInt);
                    String payLists = new Gson().toJson(payList);
                    payByCard(mUserId, orderIdInt, payLists, totalMoney);
                }
                break;
        }
    }


    Account account = null;
    AccountAdapter accountAdapter = null;
    List<Account.DataBean> accountList = new ArrayList<Account.DataBean>();

    public void accoutByRelated(String userId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token", mToken);
        lRequest.addParam("userId", userId);
        lRequest.addParam("accTypes", "1,6,7,10");
        lRequest.setUri(ServerPort.ACC_BY_RELATED);
        lRequest.setUriType(UrlsTools.ACCOUNT_INFO);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null) {
                    Log.d(TAG, "responseBean222==" + responseBean);
                    account = new Gson().fromJson(responseBean, Account.class);
                    if (account != null) {
                        if (account.getData() != null && account.getData().size() > 0) {
                            accountList = account.getData();
//                            dataBean = new Account.DataBean();
//                            dataBean.setAccid("5");
//                            dataBean.setAcctype(5);
//                            dataBean.setCardName("支付宝");
//                            accountList.add(dataBean);
                            accountAdapter = new AccountAdapter(getApplicationContext(), accountList);
                            paySp.setAdapter(accountAdapter);
                        }
                    }
                }
            }
        });
    }

    public void payByCard(String userId, int orderid, String payList, double totalFee) {
        try {
            LRequest lRequest = new LRequest();
            lRequest.addParam("token", mToken);
            lRequest.addParam("userId", userId);
            lRequest.addParam("orderId", orderid);
            lRequest.addParam("paylist", URLEncoder.encode(payList, "utf-8"));
            lRequest.addParam("totalFee", totalFee);
            lRequest.setUri(ServerPort.PAY_BY_CARD);
            lRequest.setUriType(UrlsTools.FOOD_INFO);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
                }

                @Override
                public void onNext(String responseBean, String code) {
                    if ("0".equals(code)) {
                        Log.d(TAG, "responseBean==" + responseBean);
                        T.showAnimToast(getApplicationContext(), "支付成功，祝您用餐愉快，谢谢！");
                        onBackPressed();
                    } else {
                        T.showAnimToast(getApplicationContext(), "支付失败，请重新支付！");
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showProgress() {
        try {
            showProgress(FoodOrderPayActivity.this);
        } catch (Exception E) {

        }
    }

    @Override
    public void hideProgress() {
        try {
            closeProgress();
        } catch (Exception E) {

        }
    }

    @Override
    protected int getlayout() {
        return R.layout.llh_order_pay;
    }

    String mToken, mUserId;

    @Override
    protected void initView() {
        mUserId = SharedPreferenceUtil.getUserInfo("customerId", getApplicationContext());
        mToken = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR, getApplicationContext());
    }

    @Override
    protected void doBasess() {

    }

    @Override
    protected INetRequestManager getRequestManager() {
        return NetRequestManager.getInstance();
    }


}
